<-- 用法：
1、安装
  npm install xlsx --save
2、调用
import importExcel from '@/views/app/biz/common/importExcel'

<a-button type="primary" @click="onImportData" icon="vertical-align-top"> 导入数据 </a-button>
<import-excel ref="import"  @onSubmit="onSubmitExcel" >此处可以加自定义按钮用于下载模板等操作</import-excel>

//method里
    onImportData(){
      //导入excel预览列表的columns,要求title值和excel表头值一一对应 require:true表示该列为必填
      const excelColumns = [
        { title: '序号', dataIndex: 'key', key: 'key', require:false,align: 'center' },
        { title: '一级分类（学科、\n品类）', dataIndex: 'first', key: 'first', require:false,align: 'center' },
        { title: '二级分类（用途、品\n目）', dataIndex: 'second', key: 'second', require:true,align: 'center' },
        { title: '三级分类（部位、功能、\n品种）', dataIndex: 'third', key: 'third', require:true,align: 'center' },
        { title: '医保耗材代码', dataIndex: 'medicareCode', key: 'medicareCode', require:false,align: 'center' },
        { title: '医保通用名', dataIndex: 'commonName', key: 'commonName', require:false,align: 'center' },
        { title: '耗材材质', dataIndex: 'disc', key: 'disc', require:false,align: 'center' },
        { title: '耗材生产企业', dataIndex: 'manufacturerZh', key: 'manufacturerZh', require:false,align: 'center' },
        { title: '规格（特征、参数）', dataIndex: 'spec', key: 'spec', require:false,align: 'center' },
        // {
        //   title: '操作',
        //   dataIndex: 'action',
        //   width: 100,
        //   key: 'operation',
        //   align: 'center',
        //   scopedSlots: { customRender: 'action' }
        // }
      ]
      this.$refs.import.showModal(excelColumns)
    },
    //提交导入数据
    async onSubmitExcel(val){
      console.log(val);
      //执行提交数据代码，提交成功后执行this.$refs.import.closeModal2()
      let key = 'updatable'
      this.$message.loading({ content: '正在导入中', key })
      // let res = await saveInfo(val)
      let res = {code:'C1',data:[]}
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        this.$message.success({ content: '导入成功',key, duration: 3 })
        this.$refs.import.closeModal2()
        this.getList(this.q_formDatas)
      } else {
        this.$message.error({ content: '导入失败,请稍后再试',key, duration: 3 })
      }
      
    },
-->
<template>
    <basic-modal 
        :modalOpt="modal" 
        :footer="footer"
        :buttonText="['导入','取消']"
        @onMakeSure="onSubmit"
        @closeModal="closeModal">
        <template>
            <div class="importBox">
                <span style="marginRight:20px"><slot name="cusBtn"></slot></span>
                <a-upload
                  :file-list="fileList" 
                  :before-upload="beforeUpload"
                  :remove="onInitData"
                  :multiple="true"
                >
                  <a-button @click="onTouch"> <a-icon type="upload" /> 选择数据 </a-button>
                </a-upload>
            </div>
            <div class="recordBox" v-if="listdata.length">
                <a-list-table
                    :columns="viewColumns"
                    :tableData="listdata"
                    :pagination="pagination"
                    :isSelecttion="false"
                    :loading="loading"
                    :scroll="{ y: 450 }"
                    @onAction="onAction"
                    @onTableChange="handleTableChange"
                >
                </a-list-table>
            </div>
        </template>
    </basic-modal>
</template>

<script>
import basicModal from './basicModal.vue'
import basicForm from './basicForm.vue'
import aListTable from './aListTable.vue'
import batchOperatBtn from './batchOperatBtn.vue'
import XLSX from 'xlsx'
import storage from 'store'
export default {
  components: {
    basicModal,
    basicForm,
    aListTable,
    batchOperatBtn,
    
  },
  data() {
    return {
      footer:undefined,
      loading: false,
      modal: {
        modalVisible: false,
        modalTitle: '',
        modalWidth: '90vw',
        maxHeight:'80vh'
      },
      listdata: [],
      pagination: {
        //分页配置
        current: 1, //当前页码 current
        pageSize: 10, //每页显示条数 pageSize
        total: 0,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['2', '10', '50', '100'],
      },
      fileList:[], //文件列表
      excelContent:[], //文件内容
      columns:[
          // { title: '序号', dataIndex: 'key', key: 'key', align: 'center',},
          // { title: '一级分类（学科、\n品类）', dataIndex: 'first', key: 'first', align: 'center',},
          // { title: '操作',dataIndex: 'action',width: 100,key: 'operation',align: 'center',scopedSlots: { customRender: 'action' },},
        ],
      //用于显示的columns,view为true表示显示
      viewColumns:[]
    }
  },
  computed: {},
  mounted() {},
  methods: {
    showModal(columns) {
      console.log('点击了导入')
      this.columns=columns
      this.viewColumns=[]
      for (const item of columns) {
        if (item.view) {
          this.viewColumns.push(item)
        }
      }
      this.onInitData()
      this.modal.modalVisible = true
      this.modal.modalTitle = '导入数据预览'

    },
    onInitData(){
      this.listdata=[]
      this.fileList=[]
      this.loading=false
      this.getTotal()
    },
    // 关闭模态详细框
    closeModal() {
      this.modal.modalVisible = false
      this.$emit('close')
    },
    // 保存成功关闭模态详细框
    closeModal2() {
      this.modal.modalVisible = false
      this.$emit('ok')
    },
    onTouch(){

    },
    //选择文件夹后
    beforeUpload(file){
      console.log(file);
      const types = file.name.split('.')[1]
      const fileType = ['xlsx', 'xlc', 'xlm', 'xls', 'xlt', 'xlw', 'csv'].some(item => item === types)
      if (!fileType) {
        this.$message.error({ content: '格式错误！请重新选择',duration: 3 })
        this.onInitData()
        return
      }
      this.loading=true
      //单文件上传
      this.fileList=[file]
      //多文件上传
      // this.fileList = [...this.fileList, file];
      this.file2Xce(file).then(tabJson => {
        if (tabJson && tabJson.length > 0) {
          this.excelContent = tabJson[0].sheet
          let data=[]
          outloop:
          // this.excelContent.forEach((item, index, arr) => {
          for (let index in this.excelContent) { 
            console.log(item);
            let item=this.excelContent[index]
            let alist={}
            for (let col of this.columns) {
              //如果columns的该字段在excel中某一行能找到值，则赋值，否则判断是否为必填，必填报错，否则为null
              if(item[col.title]){
                alist[col.dataIndex]=item[col.title]
              }else{
                console.log(col.title,item[col.title]);
                //检测到必填项未填数据时
                if (col.require) {
                  data=[]
                  this.fileList=[]
                  this.$message.error({ content:'excel表格中第'+(parseInt(index)+2)+'行的“'+col.title+ '”为必填项，请完善表格后重新导入',duration: 3 })
                  break outloop;
                }else{
                  alist[col.dataIndex]=null
                }
                
              }
            }
            data.push({
              ...alist,
              key: parseInt(index)+1,
              // action: ['删除']
            })
          }
          console.log(data);
          this.listdata=data
          this.getTotal()
          this.loading=false
          
        }
      })
    },
    file2Xce (file) {
      return new Promise(function (resolve, reject) {
        const reader = new FileReader()
        reader.onload = function (e) {
          const data = e.target.result
          this.wb = XLSX.read(data, {
            type: 'binary'
          })
          const result = []
          this.wb.SheetNames.forEach((sheetName) => {
            result.push({
              sheetName: sheetName,
              sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName])
            })
          })
          resolve(result)
        }
        // reader.readAsBinaryString(file.raw) // 传统input方法
        reader.readAsBinaryString(file) 
      })
    },
    getTotal(){
      const pagination = { ...this.pagination }
      pagination.total = this.listdata.length
      this.pagination = pagination
      this.pagination.showTotal =  (showTotal) => {return `共 ${showTotal} 条`}
    },
    // 触发改变页码,筛选,排序时的回调
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
    },
    
    // 模态详细框提交按钮，返回数据文件位置信息
    onSubmit() {
      if(this.listdata.length){
        this.onSubmitFile()
        this.onImportData()
      }else{
        this.$message.warn({ content: '未添加数据', duration: 2 })
      }
    },
    // 模态详细框提交按钮,返回数据文件
    onSubmitFile(){
      const { fileList } = this;
      const formData = new FormData();
      fileList.forEach(file => {
        console.log(file);
        formData.append('orgCode', storage.get('orgCode'));
        formData.append('orgName', storage.get('orgName'));
        formData.append('vfile', file);
      });
      // for (let [a, b] of formData.entries()) {
      //     console.log(a, b);
      // } 
      //点击返回formData
      this.$emit('onSubmit',formData,file)
    },
    // 模态详细框提交按钮,返回数据数组
    onImportData() {
      if(this.listdata.length){
        // this.saveObjInfo(this.listdata)

        this.$emit('onImportData',this.listdata)
      }else{
        this.$message.warn({ content: '未添加数据', duration: 2 })
      }
    },
    //删除数据
    onAction(text, record, index) { 
      console.log(text, record, index)
      if (text == '删除') {
        let optInd=this.listdata.findIndex(item=>{
          return item.key==record.key
        })
        this.listdata.splice(optInd, 1)
        this.getTotal()
      }
    },
  },
}
</script>

<style>
.ant-upload-list{
  display: inline-block;
  width: 50%;
  margin-left: 10px;

}
.importBox .ant-upload-list-item{
  margin-top: 0px;
}
.importBox .ant-upload-list-item-info{
  height: 32px;
  display: flex;
  align-items: center;
}
.importBox .ant-upload-list-item-name{
  height: 100%;
  display: flex;
  align-items: center;
}
.importBox .ant-upload-list-item-card-actions{
  top: 3px;
}
.importBox .anticon{
  margin-top: 5px;
}
</style>